package com.wjk.easy.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by wujiankun on 2017/12/4.
 * 通用工具类
 */

public class CommonUtil {
    public static String getStringMD5(String sourceStr) {
        String s = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            //这两行代码的作用是：
            // 将bytes数组转换为BigInterger类型。1，表示 +，即正数。
            BigInteger bigInt = new BigInteger(1, md.digest(sourceStr.getBytes()));
            // 通过format方法，获取32位的十六进制的字符串。032,代表高位补0 32位，X代表十六进制的整形数据。
            //为什么是32位？因为MD5算法返回的时一个128bit的整数，我们习惯于用16进制来表示，那就是32位。
            s = String.format("%032x", bigInt);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static void showWeatherIcoDay(Context context, String weatherCode, ImageView imageView) {
        Glide.with(context).load("file:///android_asset/ico_new/" + weatherCode + ".png").into(imageView);
    }

    public static void showWeatherIcoNight(Context context, String weatherCode, ImageView imageView) {
        if (isAssetFileExists(context, weatherCode + "1.png")) {
            Glide.with(context).load("file:///android_asset/ico_new/" + weatherCode + "1.png").into(imageView);
        } else {
            showWeatherIcoDay(context, weatherCode, imageView);
        }
    }


    /**
     * 判断assets文件夹下的文件是否存在
     *
     * @return false 不存在    true 存在
     */
    public static boolean isAssetFileExists(Context context, String filename) {
        AssetManager assetManager = context.getAssets();
        try {
            String[] names = assetManager.list("ico_new");
            for (int i = 0; i < names.length; i++) {
                if (names[i].equals(filename.trim())) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    public static boolean isNightNow() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        return isNightNow(hour);
    }

    public static boolean isNightNow(int hour) {
        boolean r;
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH) + 1;
        if (month >= 11 || month <= 3) {
            r = hour >= 17 || hour < 6;
        } else {
            r = hour >= 18 || hour < 5;
        }
        return r;
    }

    public static ViewGroup showTheDialog(Context context, int layoutId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        //自定义布局
        LayoutInflater inflater = LayoutInflater.from(context);
        ViewGroup view = (ViewGroup) inflater.inflate(layoutId, null);
        builder.setView(view);
        builder.show();
        return view;
    }

    public static String getFileDir(Context context) {
        /*String filePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            filePath = context.getExternalFilesDir().getPath();
        } else {
            filePath = context.getCacheDir().getPath();
        }
        return filePath;*/
        return getFileDir(context);
    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm
     *
     * @param strDate
     * @return
     */
    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    public static String dateToStr(Date date) {
        DateFormat dateTimeInstance = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA);
        return dateTimeInstance.format(date);
    }

    public static String dateToStr(Date date,String pattern) {
        DateFormat dateTimeInstance = new SimpleDateFormat(pattern, Locale.CHINA);
        return dateTimeInstance.format(date);
    }


    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        return resources.getDimensionPixelSize(resourceId);
    }

    public static void setSpValue(Context context,String key,String value){
        SharedPreferences easy = context.getSharedPreferences("easy", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = easy.edit();
        editor.putString(key,value);
        editor.apply();
    }

    public static String getSpValue(Context context,String key){
        SharedPreferences easy = context.getSharedPreferences("easy", Context.MODE_PRIVATE);
        return easy.getString(key, "");
    }
    /**
     * 设置每个阶段时间
     */
    private static final int seconds_of_1minute = 60;

    private static final int seconds_of_30minutes = 30 * 60;

    private static final int seconds_of_1hour = 60 * 60;

    private static final int seconds_of_1day = 24 * 60 * 60;

    private static final int seconds_of_15days = seconds_of_1day * 15;

    private static final int seconds_of_30days = seconds_of_1day * 30;

    private static final int seconds_of_6months = seconds_of_30days * 6;

    private static final int seconds_of_1year = seconds_of_30days * 12;

    /**
     * 格式化时间
     *
     * @param mTime
     * @return
     */
    public static String getTimeRange(String mTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        /*获取当前时间*/
        Date curDate = new Date(System.currentTimeMillis());
        String dataStrNew = sdf.format(curDate);
        Date startTime = null;
        try {
            /**将时间转化成Date*/
            curDate = sdf.parse(dataStrNew);
            startTime = sdf.parse(mTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        /*除以1000是为了转换成秒*/
        long between = (curDate.getTime() - startTime.getTime()) / 1000;
        int elapsedTime = (int) (between);
        if (elapsedTime < seconds_of_1minute) {

            return "刚刚";
        }
        if (elapsedTime < seconds_of_30minutes) {

            //return elapsedTime / seconds_of_1minute + "分钟前";
            return "刚刚";
        }
        if (elapsedTime < seconds_of_1hour) {

            return "半小时前";
        }
        if (elapsedTime < seconds_of_1day) {

            return elapsedTime / seconds_of_1hour + "小时前";
        }
        if (elapsedTime < seconds_of_15days) {

            return elapsedTime / seconds_of_1day + "天前";
        }
        if (elapsedTime < seconds_of_30days) {

            return "半个月前";
        }
        if (elapsedTime < seconds_of_6months) {

            return elapsedTime / seconds_of_30days + "月前";
        }
        if (elapsedTime < seconds_of_1year) {

            return "半年前";
        }
       /* if (elapsedTime >= seconds_of_1year) {

            return elapsedTime / seconds_of_1year + "年前";
        }*/
        return null;
    }

    /**
     * 判断两个日期是否是同一天
     *
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameDay(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        if(cal1.get(Calendar.DAY_OF_MONTH)==cal2.get(Calendar.DAY_OF_MONTH)){
            //同一天
            if(cal1.get(Calendar.MONTH)==cal2.get(Calendar.MONTH)){
                //同一月份
                if(cal1.get(Calendar.YEAR)==cal2.get(Calendar.YEAR)){
                    //同一年份
                    return true;
                }
            }
        }
        return false;
    }
}
